<?php namespace App\Services\Wechat;

use App\ActiveResult;
use App\Exceptions\NotFoundException;
use App\Exceptions\RedPackageException;
use App\OrderItem;
use App\Orders;
use App\RedPackageOrder;
use App\RedPackageRecord;
use App\Services\Tools;
use App\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Illuminate\Support\Facades\DB;
use Log;

class WechatRedPackage
{
    /**
     * 生成红包邀请码
     * @param User $userModel
     * @param Orders $orderModel
     * @return RedPackageOrder|bool
     * @throws NotFoundException
     */
    public static function buildRedPackageOrder(Orders $orderModel){

        if((int)$orderModel->ispay == 0)
            return false;

//        if(time() < 1475251200)
//            return false;

        $thatOrderItem = $orderModel->orderItems()->where('pid','=',0)->first();
        if(!$thatOrderItem)
            throw new NotFoundException(NotFoundException::OrderNotFound);

        /** @var OrderItem $thatOrderItem */
        $thatCommodity = $thatOrderItem->commodity;

        /** @var User $thatUser */
        $thatUser = $orderModel->user;

        if(!$thatCommodity)
            throw new NotFoundException(NotFoundException::CommodityNotFound);

        if((int)$thatCommodity->can_custom == 0)
            return false;

        $newRedPackageOrder = RedPackageOrder::whereOrderId($orderModel->id)->first();
        if(!$newRedPackageOrder){
            $amount = (float)$orderModel->s_amount - (float)$orderModel->p_amount;

            /** @var ActiveResult $userReward */
            $userReward = ActiveResult::whereUserId($thatUser->id)->orderBy('created_at','desc')->first();

            $pre_money = 0;
            if($userReward){
                switch($userReward->level){
                    case '1':
                        $pre_money = (float)$amount * 0;
                        break;
                    case '2':
                        $pre_money = (float)$amount * 0.1;
                        break;
                    case '3':
                        $pre_money = (float)$amount * 0.05;
                        break;
                }
            }

            $pre_money = round($pre_money);
            if((float)$pre_money > 0){
                $Code = null;
                while(true){
                    $Code = Tools::makeRedPackageCode();
                    $thisCode = RedPackageOrder::whereCode($Code)->first();
                    if(!$thisCode)break;
                }

                $newRedPackageOrder = new RedPackageOrder();
                $newRedPackageOrder->order_id = $orderModel->id;
                $newRedPackageOrder->build_user_id = $orderModel->user_id;
                $newRedPackageOrder->pre_money     = $pre_money;
                $newRedPackageOrder->has_money     = $pre_money;
                $newRedPackageOrder->all_num       = $thatOrderItem->number;
                $newRedPackageOrder->has_num       = $thatOrderItem->number;
                $newRedPackageOrder->code          = $Code;
                $newRedPackageOrder->status        = 1;
                $newRedPackageOrder->save();
            }
        }

        return $newRedPackageOrder;
    }

    /**
     * @param User $userModel
     * @param $code
     * @return RedPackageOrder
     * @throws RedPackageException
     */
    public static function getRedPackageByCode(User $userModel,$code){

        /** @var RedPackageOrder $thatRedPackage */
        $thatRedPackage = RedPackageOrder::whereCode($code)->whereStatus(1)->first();
        if(!$thatRedPackage)
            return '该兑换码不存在哦！';

        /*启用事物*/
        $result = DB::transaction(function () use ($thatRedPackage,$userModel,$code){
            $thatRedPackageRecord = RedPackageRecord::whereCode($code)->whereUserId($userModel->id)->first();

            if($thatRedPackageRecord)
                return '不可以贪心哦，您已经领取过该红包了！';

            if((int)$thatRedPackage->has_num <= 0)
                return '该红包已截止派送了！';

            //$money = self::getRandomMoney((float)$thatRedPackage->has_money,(int)$thatRedPackage->has_num);
            $money = (float)$thatRedPackage->has_money / (float)$thatRedPackage->has_num;

            $result = self::sendRedPackage($userModel->openid,$money);

            if($result->err_code == 'SUCCESS'){
                $thatRedPackage->has_num    = (int)$thatRedPackage->has_num - 1;
                $thatRedPackage->has_money  = (float)$thatRedPackage->has_money - (float)$money;
                $thatRedPackage->last_money = (float)$thatRedPackage->has_money + (float)$money;
                $thatRedPackage->save();

                $thatRedPackageRecord = new RedPackageRecord();
                $thatRedPackageRecord->user_id  = $userModel->id;
                $thatRedPackageRecord->code     = $code;
                $thatRedPackageRecord->bill_num = $result->mch_billno;
                $thatRedPackageRecord->money    = $money;
                $thatRedPackageRecord->save();

                $result = '派送成功';
            }else{
                $result = '咦~系统懵逼了，稍等再试或联系客服！';
            }

            return $result;
        });

        return $result;
    }

    public static function getRandomMoney($money,$size){
        $min = 1;

        if((int)$size == 1){
            $money = round($money * 100) / 100;
            $money = $money <= $min ? 1 : $money;
            return $money;
        }

        $max = $money / $size * 2;
        $r   = self::getRandomNum();
        $money = $r * $max;
        $money = round($money * 100) / 100;
        $money = $money <= $min ? 1 : $money;

        return $money;
    }

    public static function getRandomNum(){
        $max = 1;
        $min = 0;
        $b = 0;
        while(true){
            $a = $min + mt_rand()/mt_getrandmax() * ($max-$min);
            $b = round($a,2);
            if($b !== 0)
                break;
        }

        return $b;
    }

    public static function sendRedPackage($openid,$money){
        $app    = app("wechat");
        $luckyMoney = $app->lucky_money;

        $luckyMoneyData = [
            'mch_billno'       => Tools::makeBillNum(),
            'send_name'        => '乐自造团体服返现红包',
            're_openid'        => $openid,
            'total_num'        => 1,  //固定为1，可不传
            'total_amount'     => $money * 100,  //单位为分，不小于300
            'wishing'          => '乐自造－专业个性定制服务商',
            'act_name'         => '乐自造优惠活动',
            'remark'           => '测试备注',
        ];
        $result = $luckyMoney->sendNormal($luckyMoneyData);

        return $result;
    }
}